{{ $bookSection := default "docs" .Site.Params.BookSection  }}
{{ if eq $bookSection "*" }}
  {{ $bookSection = "/" }}{{/* Backward compatibility */}}
{{ end }}

{{ with .Site.GetPage $bookSection }}
  {{ template "book-section-children" (dict "Section" . "CurrentPage" $) }}
{{ end }}

{{ define "book-section-children" }}{{/* (dict "Section" .Section "CurrentPage" .CurrentPage) */}}
  <ul>
    {{ range (where .Section.Pages "Params.bookHidden" "ne" true) }}
      {{ if .IsSection }}
        <li {{- if .Params.BookFlatSection }} class="book-section-flat" {{ end -}}>
          {{ template "book-page-link" (dict "Page" . "CurrentPage" $.CurrentPage) }}
          {{ template "book-section-children" (dict "Section" . "CurrentPage" $.CurrentPage) }}
        </li>
      {{ else if and .IsPage .Content }}
        <li>
          {{ template "book-page-link" (dict "Page" . "CurrentPage" $.CurrentPage) }}
        </li>
      {{ end }}
    {{ end }}
  </ul>
{{ end }}

{{ define "book-page-link" }}{{/* (dict "Page" .Page "CurrentPage" .CurrentPage) */}}
  {{ $current := eq .CurrentPage .Page }}
  {{ $ancestor := .Page.IsAncestor .CurrentPage }}

  {{ if .Page.Params.BookCollapseSection }}
    <input type="checkbox" id="section-{{ md5 .Page }}" class="toggle" {{ if or $current $ancestor }}checked{{ end }} />
    <label for="section-{{ md5 .Page }}" class="flex">
      <a {{ if .Page.Content }}href="{{ .Page.RelPermalink }}"{{ else }}role="button"{{ end }} class="{{ if $current }}active{{ end }}">
        {{ template "book-icon-title" .Page -}}
      </a>
      <img src="{{ partial "docs/icon" "chevron-right" }}" class="book-icon" />
    </label>
  {{ else if .Page.Params.BookHref }}
    <a href="{{ .Page.Params.BookHref }}" class="{{ if $current }}active{{ end }}" target="_blank" rel="noopener">
      {{ template "book-icon-title" .Page -}}
    </a>
  {{ else if .Page.Content }}
    <a href="{{ .Page.RelPermalink }}" class="{{ if $current }}active{{ end }}">
      {{ template "book-icon-title" .Page -}}
    </a>
  {{ else }}
    <a>
      {{ template "book-icon-title" .Page -}}
    </a>
  {{ end }}
{{ end }}

{{ define "book-icon-title" }}
{{- with .Page.Params.BookIcon -}}
  <img src="{{ partial "docs/icon" . }}" class="book-icon" />
{{- end -}}
{{- partial "docs/title" .Page -}}
{{ end }}